<template>
  <div id="content">
    <globle-linear-border>
      <el-card class="searchBox">
        <el-form :inline="true">
          <el-form-item label="教师姓名">
            <el-input v-model="pageQuery.otherParams.tchName" placeholder="输入教师姓名搜索" clearable />
          </el-form-item>
          <el-form-item label="课程名称">
            <el-input v-model="pageQuery.otherParams.courseName" placeholder="输入教学班搜索" clearable />
          </el-form-item>
          <el-form-item label="开课学院">
            <el-input v-model="pageQuery.otherParams.openCollege" placeholder="输入开课学院搜索" clearable />
          </el-form-item>
          <el-form-item label="地点">
            <el-input v-model="pageQuery.otherParams.place" placeholder="输入教学地点搜索" clearable />
          </el-form-item>
          <el-form-item label="学分">
            <el-input v-model="pageQuery.otherParams.credit" placeholder="输入学分搜索" clearable />
          </el-form-item>
          <el-form-item label="周数">
            <el-select v-model="week" clearable multiple collapse-tags placeholder="选择上课周数"
              @change="onSelectChange('week')">
              <el-option v-for="item in 16" :key="item" :label="item + '周'" :value="item" />
            </el-select>
          </el-form-item>
          <el-form-item label="星期">
            <el-select v-model="weekDay" clearable multiple collapse-tags placeholder="选择星期"
              @change="onSelectChange('weekDay')">
              <el-option v-for="item in 7" :key="item" :label="chineseWeedDay(item)" :value="item" />
            </el-select>
          </el-form-item>
          <el-form-item label="课程序号">
            <el-select v-model="orderNum" clearable multiple collapse-tags placeholder="选择课程的序号"
              @change="onSelectChange('orderNum')">
              <el-option v-for="item in 12" :key="item" :label="chineseOrderNum(item)" :value="item" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <section>
              <el-button type="primary" icon="Search" @click.stop="onSearch">搜 索</el-button>
              <el-button type="warning" icon="RefreshRight" @click.stop="reset">重 置</el-button>
            </section>
          </el-form-item>
        </el-form>
      </el-card>
    </globle-linear-border>

    <globle-linear-border style="margin-top: 20px">
      <el-card class="mainBox">
        <span v-if="tableData.rows">
          <el-table :border="true" stripe :data="tableData.rows" cell-class-name="table-cell"
            header-cell-class-name="table-header-cell" empty-text="暂未开放选课">
            <el-table-column  label="学年" width="130">
              <template #default="scope">{{ scope.row.schoolYear }}{{ scope.row.stage }}</template>
            </el-table-column>
            <!-- <el-table-column property="studentId" label="代码" width="140" show-overflow-tooltip /> -->
            <el-table-column property="courseName" label="课程名称" />
            <el-table-column property="tchName" label="教师名称" />
            <el-table-column property="teachClass" label="教学班" />
            <el-table-column property="week" label="周数" />
            <el-table-column property="weekDay" label="星期" />
            <el-table-column property="orderNum" label="序号" />
            <el-table-column property="place" label="地点" width="140" show-overflow-tooltip />
            <el-table-column property="classHourType" label="学时类型" />
            <el-table-column property="courseType" label="开课类型" />
            <el-table-column property="stuClass" label="已选人数" width="90">
              <template #default="scope">{{ scope.row.selectedNum }}/{{ scope.row.maxPerson }}</template>
            </el-table-column>
            <el-table-column fixed="right" width="170" label="操作">
              <template #default="scope">
                <el-button class="co-select" type="primary" size="small" @click.stop="onCheck(scope.row)">详情</el-button>
                <el-button v-if="!scope.row.selectedId" :loading="selectLoading" class="co-select" type="success"
                  size="small" @click.stop="onSelectCourse(scope.row)">选课</el-button>
                <el-button v-else class="co-select" :loading="selectLoading" type="danger" size="small"
                  @click.stop="onCancelSelected(scope.row)">退选</el-button>
              </template>
            </el-table-column>
          </el-table>
          <el-pagination v-model:currentPage="pageQuery.pageParams.pageNum"
            v-model:page-size="pageQuery.pageParams.pageSize" :page-sizes="pageSizeOption" :background="true"
            :small="true" layout="total, sizes, prev, pager, next, jumper" :total="tableData.totalSize"
            @size-change="onSizeChange" @current-change="onCurrentChange" />
        </span>
      </el-card>
    </globle-linear-border>

    <!-- 详情 -->
    <detail ref="detailRef"></detail>
  </div>
</template>

<script lang="ts" setup>
import { computed, onMounted, reactive, ref } from 'vue';
import { ElMessage, ElNotification, ElTable } from 'element-plus';
import { ICoursePageParams, IPageRes, APIData, ICoSelectedParams, ICoSeDeleteParams } from '../../../type';
import { useUserStore } from '../../../store/user';
import { useAPI } from '../../../request/api';
import { useUtils } from '../../../utils/index'
import Detail from './Detail.vue';
const store = useUserStore();
const api = useAPI();
const utils = useUtils();

onMounted(() => {
  const schoolYearStage = utils.getNowSchoolYearStage();
  pageQuery.otherParams.stage = schoolYearStage.stage;
  pageQuery.otherParams.schoolYear = schoolYearStage.schoolYear;
  getPageInfo();
  console.log(pageQuery.otherParams);
});

const detailRef = ref();
const selectLoading = ref(false);
const week = ref([] as any);
const weekDay = ref([] as any);
const orderNum = ref([] as any);
const tableData = ref({} as IPageRes);
const pageSizeOption = [5, 10, 15, 20];
const pageQuery = reactive<ICoursePageParams>({
  otherParams: {
    place: '',
    tchName: '',
    courseName: '',
    openCollege: '',
    credit: '',
    week: '',
    weekDay: '',
    orderNum: '',
    // 以上是用户输入，以下是默认设置
    courseIsBegin: 1,
    studentId: store.userInfo.studentId,  //用于查询每个课程是否已选
    allowBand: store.userInfo.college,
    grade: store.userInfo.grade,
    stage: '',
    schoolYear: '',
    // workId: ''
    //teachClass: ''
  },
  pageParams: {
    pageNum: 1,
    pageSize: pageSizeOption[1],
    sortField: '',
    sortType: '',
  },
});

// 详情按钮
const onCheck = (row: any) => {
  detailRef.value.openByCheck(row);
}

// 选课按钮
const onSelectCourse = async (row: any) => {
  // console.log('row',row);
  selectLoading.value = true;
  const data: ICoSelectedParams = { studentId: store.userInfo.studentId, courseId: row.id }
  const res: APIData = await api.coSelection.save(data);
  if (res.code === 200) {
    ElNotification({
      title: '选课成功',
      message: `您已成功选课：${row.teachClass}`,
      type: 'success',
    })
    await getPageInfo();
    selectLoading.value = false;
  } else {
    ElMessage.error(res.message);
    selectLoading.value = false;
  }
}

// 退选按钮
const onCancelSelected = async (row: any) => {
  selectLoading.value = true;
  const data:ICoSeDeleteParams = {
    coSeIdList: [row.selectedId],
    courseIdList: [row.id]
  };
  const res: APIData = await api.coSelection.delete(data);
  if (res.data) {
    ElNotification({
      title: '退选成功',
      message: `您已成功退选：${row.courseName}`,
      type: 'success',
    })
    await getPageInfo();
    selectLoading.value = false;
  } else {
    ElMessage.error(res.message);
    selectLoading.value = false;
  }
}

//搜索按钮
const onSearch = () => {
  pageQuery.pageParams.pageNum = 1;
  pageQuery.pageParams.pageSize = pageSizeOption[1];
  getPageInfo();
}

// 重置按钮
const reset = () => {
  const schoolYearStage = utils.getNowSchoolYearStage();
  pageQuery.otherParams = {
    place: '',
    tchName: '',
    courseName: '',
    openCollege: '',
    credit: '',
    week: '',
    weekDay: '',
    orderNum: '',
    courseIsBegin: 1,
    studentId: store.userInfo.studentId,
    allowBand: store.userInfo.college + store.userInfo.major,
    grade: store.userInfo.grade,
    workId: '',
    stage: schoolYearStage.stage,
    schoolYear: schoolYearStage.schoolYear,
  }
  pageQuery.pageParams = {
    pageNum: 1,
    pageSize: pageSizeOption[1],
    sortField: '',
    sortType: ''
  }
  week.value = []
  weekDay.value = []
  orderNum.value = []
  getPageInfo();
}

// 当多选框条件改变时触发
const onSelectChange = (type: string) => {
  if (type == 'week') pageQuery.otherParams.week = week.value.join(',')
  if (type == 'weekDay') pageQuery.otherParams.weekDay = weekDay.value.join(',')
  if (type == 'orderNum') pageQuery.otherParams.orderNum = orderNum.value.join(',')
}

// 转中文星期  计算属性
const chineseWeedDay = computed(() => {
  return (weekDay: number) => {
    switch (weekDay) {
      case 1: return '星期一';
      case 2: return '星期二';
      case 3: return '星期三';
      case 4: return '星期四';
      case 5: return '星期五';
      case 6: return '星期六';
      case 7: return '星期天';
    }
  }
})

// 转中文课程序号  计算属性
const chineseOrderNum = computed(() => {
  return (orderNum: number) => {
    switch (orderNum) {
      case 1: return '第一节';
      case 2: return '第二节';
      case 3: return '第三节';
      case 4: return '第四节';
      case 5: return '第五节';
      case 6: return '第六节';
      case 7: return '第七节';
      case 8: return '第八节';
      case 9: return '第九节';
      case 10: return '第十节';
      case 11: return '第十一节';
      case 12: return '第十二节';
    }
  }
})

//根据当前时间计算学年和期数
// const getSchoolYearStage = () => {
//   const timeList = new Date().toLocaleDateString().split('/');  //  ['2023','1','14']  2022-2023的第一学期   ['2023','2','14']  2022-2023的第二学期  
//   const year = Number(timeList[0]);
//   const month = Number(timeList[1]);
//   const day = Number(timeList[2]);
//   if (month >= 2 && day >= 1 && month <= 8 && day <= 31) {
//     schoolYearStage.schoolYear = `${year - 1}-${year}`;
//     schoolYearStage.stage = '2'
//   }
//   if (month >= 9 && day >= 1) {
//     schoolYearStage.schoolYear = `${year}-${year + 1}`;
//     schoolYearStage.stage = '1'
//   }
//   if (month <= 1 && day <= 31) {
//     schoolYearStage.schoolYear = `${year - 1}-${year}`;
//     schoolYearStage.stage = '1'
//   }
// }

//分页大小
const onSizeChange = (val: number) => {
  pageQuery.pageParams.pageSize = val;
  pageQuery.pageParams.pageNum = 1;
  getPageInfo();
};
//分页页码
const onCurrentChange = (val: number) => {
  pageQuery.pageParams.pageNum = val;
  getPageInfo();
};

const getPageInfo = async () => {
  const res: APIData = await api.course.findPage(pageQuery);
  if (res.code === 200) tableData.value = res.data;
  else ElMessage.error(res.message);
};
</script>

<style lang="scss" scoped>
#content {
  height: 100%;
  padding: 14px 32px;

  .searchBox {
    &-item {
      margin-right: 10px;
    }

    // :deep(.el-form-item) {
    //   margin-bottom: 0;
    // }

    :deep(.el-card__body) {
      display: flex;
      justify-content: space-between;
    }

    section {
      display: flex;
    }

    :deep(.el-input__wrapper) {
      width: 200px;
    }

    // .el-form-item {
    //   margin-bottom: 16px;
    // }
  }

  .mainBox {
    :deep(.el-checkbox__inner) {
      background-color: var(--main-color);
      transition: background 0.3s ease;
    }

    :deep(.el-checkbox__input.is-checked .el-checkbox__inner) {
      background-color: var(--active-color);
      transition: background 0.3s ease;
    }

    .co-select {
      width: 60px;
    }
  }
}
</style>
